<template>
	<div class="wly-page">
		<el-table border @header-dragend="headerDragend">
			<el-table-column  min-width='250px' label-class-name="drag">
						<template slot="header" slot-scope="scope">
							<div class="grid-content bg-purple">
								<el-container>
									<el-header class="orgHeader" height="40px">
										<span>部门列表</span>
										<i class="el-icon-plus" @click="addDepartment" style="color: red;"></i>
									</el-header>
									<el-main>
										<!--搜索框-->
										<el-input size="mini" prefix-icon="el-icon-search" placeholder="搜索" v-model="input" clearable
											style="margin-bottom: 5px" @clear="searchDepartment" @keyup.enter.native="searchDepartment">
										</el-input>
										<el-tree :data="treeData" v-model="formData.departId" :props="{
							                              children: 'children',
							                              label: 'name'
							                        }" default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick">
											<span class="custom-tree-node" slot-scope="{ node, data }">
												<span>{{ node.label }}</span>
												<span class="custom-tree-node-action">
													<el-button type="text" size="mini" @click="() => append(data)" icon="el-icon-plus">
													</el-button>
													<el-button type="text" size="mini" @click="() => edit(data)" icon="el-icon-edit">
													</el-button>
													<el-button type="text" size="mini" @click="() => remove(node)" icon="el-icon-delete">
													</el-button>
												</span>
											</span>
										</el-tree>
									</el-main>
								</el-container>
							</div>
						</template>
			</el-table-column>
			<el-table-column  min-width='250px' label-class-name="drag">
					<template slot="header" slot-scope="scope">
						<div class="grid-content bg-purple-light">
							<el-header class="orgHeader" height="40px">
								<span>职务列表</span>
								<i class="el-icon-plus" @click="addPost({departId:depData.departId,
                        postName: depData.name,
                        name: ''})" style="color: red;"></i>
							</el-header>
							<el-main>
								<div>
									<p v-for="item in dutyData" :class="{'duty-class':true,select:item.postId === postId}" @click="queryDutyUser(item)">
									{{item.name}}
									<span class="duty-class-action">
										<el-button type="text" size="small" @click="editPost(item)" icon="el-icon-edit"></el-button>
										<el-button type="text" size="small" @click="deletePost(item)" icon="el-icon-delete"></el-button>
									</span>
									</p>
									<p v-if="dutyData.length ===0" style="text-align: center;">暂无数据</p>
								</div>
							</el-main>
						</div>
					</template>
			</el-table-column>
			<el-table-column min-width="300px" :resizable="false">
					<template slot="header" slot-scope="scope">
						<div class="grid-content bg-purple">
							<el-header class="orgHeader" height="40px">
								<span>用户列表</span>
								<i class="el-icon-edit" @click="userEditForm" style="color: red;"></i>
							</el-header>
							<el-main>
								<el-tag v-for="item in userData" :key="item.userId" style="margin: 5px" color="white" effect="light">
									{{ item.username }}
								</el-tag>
								<p v-if="userData.length ===0" style="text-align: center;">暂无数据</p>
							</el-main>
						</div>
					</template>
			</el-table-column>
			<template slot="empty"><span></span></template>
		</el-table>
		<el-dialog title="提示" :visible.sync="depDialogVisible" width="30%">
			<span>确认删除记录</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="depDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="deleteDepartment">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog title="提示" :visible.sync="postDialogVisible" width="30%">
			<span>确认删除记录</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="postDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="affirmDeletePost">确 定</el-button>
			</span>
		</el-dialog>
		<user-edit-form ref="userEdit" @editSuccess="editSuccess"></user-edit-form>
		<ADialogCom @closeDialog='closeDialog' @loadDepTree="loadDepTree" title="部门管理" comName="DepartmentForm"
			ref="ADialogCom" :dialog-open="depDialogVisible2">
		</ADialogCom>
		<ADialogCom @closeDialog='closeDialog' @handleNodeClick="handleNodeClick" title="职务管理" comName="PostMaintainForm"
			ref="ADialogCom" :dialog-open="dialogVisible2"></ADialogCom>
	</div>
</template>

<script>
	import ajax from '@api/ajax'
import {
DEPARTMENT_MAINTAIN,
POST_MAINTAIN,
QUERY_DEP_INFO,
QUERY_POST_INFO,
QUERY_USER_INFO
} from '@api/url'
import VHeader from '../../components/VHeader/VHeader'
import DepartmentForm from './DepartmentForm'
import UserEditForm from './UserEditForm'

	export default {
		components: {
			VHeader,
			UserEditForm,
			DepartmentForm
		},
		data() {
			return {
				ifUseTableButton: true,
				ifUseTableRodio: true,
				ifUseTableBase: true,
				ifUseTableOrder: false,
				isUseButton: true,
				input: '',
				treeData: [],
				formData: {
					'departId': ''
				},
				menuId: [],
				dutyData: [],
				userData: [],
				depData: {},
				postId: '',
				curDutyId:'',
				depDialogVisible: false,
				depDialogVisible2: false,
				dialogVisible2: false,
				deleteDepartId: '',
				postDialogVisible: false,
				deletePostId: '', // 删除职务id
				clickEvent: 'false'
			}
		},
		methods: {

			headerDragend(newWidth, oldWidth, column, event){
				if(newWidth<250){
					column.width = 250
				}else if(newWidth > 500){
					column.width = 500
				}

			},
			// 数据转树
			translateDataToTree(data) {
				// 没有父节点的数据
				let parents = data.filter(value => value.parentId === 'undefined' || value.parentId === '0')
				// 有父节点的数据
				let children = data.filter(value => value.parentId !== 'undefined' && value.parentId !== '0')
				// 定义转换方法的具体实现
				let translator = (parents, children) => {
					// 遍历父节点数据
					parents.forEach((parent) => {
						// 遍历子节点数据
						children.forEach((current, index) => {
							// 此时找到父节点对应的一个子节点
							if (current.parentId === parent.departId) {
								// 对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
								let temp = JSON.parse(JSON.stringify(children))
								// 让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
								temp.splice(index, 1)
								// 让当前子节点作为唯一的父节点，去递归查找其对应的子节点
								translator([current], temp)
								// 把找到子节点放入父节点的children属性中
								typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [
									current
								]
							}
						})
					})
				}
				// 调用转换方法
				translator(parents, children)
				// 返回最终的结果
				return parents
			},
			// 加载部门数据
			loadDepTree() {
				this.depDialogVisible2 = false
				ajax.post(QUERY_DEP_INFO).then(res => {
					let tree = this.translateDataToTree(res.data || [])
					this.treeData = tree
				}).catch(err => {
					console.error('查询发生错误！', err)
				}).finally(() => {})
			},
			// 查询部门的职务
			handleNodeClick(data) {
				this.dialogVisible2 = false
				this.depData = data
				let conditions = {}
				conditions.departId = data.departId
				ajax.post(QUERY_POST_INFO, conditions).then(res => {
					this.dutyData = res.data
				}).catch(err => {
					console.error('查询发生错误！', err)
				}).finally(() => {})
			},
			// 调用部门新增界面(无上级部门)
			addDepartment() {
				this.depDialogVisible2 = true
				this.$nextTick(() => {
					this.$refs.ADialogCom.aDialogComRef.DepartmentForm.showFormDialog({}, 'add', '0')
				})
			},
			// 调用部门新增界面(有上级部门)
			append(data) {
				this.depDialogVisible2 = true
				this.$nextTick(() => {
					this.$refs.ADialogCom.aDialogComRef.DepartmentForm.showFormDialog(data, 'add', '1')
				})
			},
			// 调用部门编辑页面
			edit(data) {
				this.depDialogVisible2 = true
				this.$nextTick(() => {
					this.$refs.ADialogCom.aDialogComRef.DepartmentForm.showFormDialog(data, 'edit', '1')
				})
			},
			// 查询部门信息
			searchDepartment() {
				let conditions = {}
				conditions.name = this.input
				ajax.post(QUERY_DEP_INFO, conditions).then(res => {
					let tree = this.translateDataToTree(res.data || [])
					this.treeData = tree
				}).catch(err => {}).finally(() => {})
			},
			// 点击删除按钮，将部门id存起来
			remove(node) {
				debugger
				this.deleteDepartId = node.data.departId
				this.depDialogVisible = true
			},
			// 确认删除部门调用的方法
			deleteDepartment() {
				let vm = this
				let deleteConditions = {}
				deleteConditions.departId = this.deleteDepartId
				deleteConditions.optMode = 'D'
				ajax.post(DEPARTMENT_MAINTAIN, deleteConditions).then(res => {
					this.$message.success('删除成功！')
					this.loadDepTree()
					vm.depDialogVisible = false
				}).catch(err => {
					console.error('查询发生错误！', err)
				}).finally(() => {})
			},
			// 点击编辑用户按钮，弹出用户编辑弹框
			userEditForm() {
				if (this.clickEvent === 'false') {
					this.$message.warning('请先选择职务')
					return
				}
				this.$refs.userEdit.userEditFormDialog(this.userData, this.postId, 'post')
			},
			// 打开新增职务页面
			addPost(data) {
				this.dialogVisible2 = true
				this.$nextTick(() => {
					this.$refs.ADialogCom.aDialogComRef.PostMaintainForm.showForm(this.depData, 'add', data)
				})
			},
			// 打开编辑职务页面
			editPost(data) {
				this.dialogVisible2 = true
				this.$nextTick(() => {
					this.$refs.ADialogCom.aDialogComRef.PostMaintainForm.showForm(this.depData, 'edit', data)
				})
			},
			// 点击删除按钮调用的方法，将删除id存起来
			deletePost(data) {
				this.deletePostId = data.postId
				this.deleteDepartId = data.departId
				this.postDialogVisible = true
			},
			// 确认删除职务
			affirmDeletePost() {
				let conditions = {}
				conditions.postId = this.deletePostId
				conditions.optMode = 'D'
				ajax.post(POST_MAINTAIN, conditions).then(res => {
					this.$message.success('删除成功！')
					conditions.departId = this.deleteDepartId
					this.postDialogVisible = false
					this.handleNodeClick(conditions)
				}).catch(err => {
					console.error('查询发生错误！', err)
				})
			},
			// 查询职务下的用户
			queryDutyUser(row) {
				let conditions = {}
				conditions.postId = row.postId
				this.postId = row.postId
				ajax.post(QUERY_USER_INFO, conditions).then(res => {
					this.userData = res.data.records
				}).catch(err => {
					console.error('查询发生错误！', err)
				}).finally(() => {})
				this.clickEvent = 'true'
			},
			// 用户编辑成功后调用的方法
			editSuccess(data) {
				let conditions = {}
				conditions.postId = data
				this.queryDutyUser(conditions)
			},
			closeDialog() {
				this.dialogVisible2 = false
				this.depDialogVisible2 = false
			},
			getData() {
				this.$refs.ATableRadioCom.selectRows()
			}
		},
		mounted() {
			this.loadDepTree()
		}
	}
</script>

<style scoped lang="stylus">
	.wly-page /deep/{
		.el-table__empty-block{
			display: none;
		}
		th.el-table__cell{
			vertical-align:top;
			font-weight: 400;
			&.drag{
				overflow: visible;
				&:after{
					content: '';
					    position: absolute;
					    z-index: 999;
					    top: 50%;
					    color: red;
					    display: inline-block;
					    width: 15px;
					    height: 18px;
					    background-image: url('~@asst/image/dotted.png');
						background-size: 100% 100%;
					    left: 100%;
					    transform: translateX(-50%);
				}
			}
		}
		.wly-page-col{
			min-width: 250px;
		}
		.duty-class{
			color: #666666;
			padding: 0 5px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			transition: all 0.3s;
			&.select{
				background-image: linear-gradient(270deg, #FFEBEB 0%, #FFD5DC 100%);
				border-radius: 5px;
				color: #F95160;
			}
			&:hover{
				background-image: linear-gradient(270deg, #FFEBEB 0%, #FFD5DC 100%);
				border-radius: 5px;
				color: #F95160;
			}
		}
	}

	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;
		&:hover{
			.custom-tree-node-action{
				display: inline-block;
			}
		}
		.custom-tree-node-action{
			display: none;
		}
	}

	.orgHeader {
		display: flex;
		justify-content: space-between;
		border-bottom: 2px solid whitesmoke;
		align-items: center;

	}

	/*修改子菜单的背景色：*/
	.el-menu-item {
		border-radius: 0;
		background-color: white !important;
	}

	/*字体颜色：*/
	.el-aside {
		color: #f04959;
	}

	/*鼠标悬浮时，子菜单的样式：*/
	.el-menu-item:hover {
		border-radius: 0;
		outline: 0 !important;
		color: #409EFF !important;
	}

	.el-menu-item.is-active {
		color: white !important;
		background: #f04959 !important;
		border-radius: 0 !important;
	}

	/*鼠标悬浮时，主菜单的样式：*/
	.el-submenu__title:focus,
	.el-submenu__title:hover {
		outline: 0 !important;
		color: white !important;
		background: #f04959 !important;
	}

	.el-menu-demo {
		margin: 15px 0 15px 0;
	}

	.dialog-footer {
		display: block;
		justify-content: center;
	}

	.el-menu-demo {
		margin-top: 10px
	}
</style>
